import { NzSafeAny } from "@/components/sf/type";
import { useTimeoutFn } from "@vueuse/core";
import { defineStore } from "pinia";
import { pinia } from "..";
import { GlobalStoreEnum } from "../enum";
import { ISettingState } from "../interface";
export const useSetting = defineStore(GlobalStoreEnum.SETTING, {
  state: (): ISettingState => ({
    prefix: "LC",
    title: "LC-后台管理",
    description: "111",
    logo: "",
    // 缓存页面keepAlive
    keepAlive: true,
    cachePageList: [] as string[]
  }),
  getters: {
    getTitle() {
      return this.title;
    },
    getPrefix() {
      return this.prefix;
    }
  },
  actions: {
    setSetting(data: ISettingState) {
      Object.keys(data).forEach(k => {
        this[k] = data[k];
      });
    },
    cacheOperate({ mode, name }: { mode: string; name: string }) {
      const delIndex = this.cachePageList.findIndex((v: string) => v === name);
      switch (mode) {
        case "refresh":
          this.cachePageList = this.cachePageList.filter(
            (v: string) => v !== name
          );
          break;
        case "add":
          delIndex === -1 && this.cachePageList.push(name);
          break;
        case "delete":
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
          break;
      }
    },
    /** 处理缓存路由（添加、删除、刷新） */
    handleAliveRoute({ name }: NzSafeAny, mode?: string) {
      switch (mode) {
        case "add":
          this.cacheOperate({
            mode: "add",
            name
          });
          break;
        case "delete":
          this.cacheOperate({
            mode: "delete",
            name
          });
          break;
        case "refresh":
          this.cacheOperate({
            mode: "refresh",
            name
          });
          break;
        default:
          this.cacheOperate({
            mode: "delete",
            name
          });
          useTimeoutFn(() => {
            this.cacheOperate({
              mode: "add",
              name
            });
          }, 100);
      }
    },
    /** 清空缓存页面 */
    clearAllCachePage() {
      this.cachePageList = [];
    }
  }
});

export const useSettingHooks = () => {
  return useSetting(pinia);
};
